﻿// -------------------------------------------------------------------------
//    @FileName         :    TestNFShmHashMapWithList.h
//    @Author           :    Assistant
//    @Date             :    25-9-25
//    @Email            :    assistant@openai.com
//    @Module           :    TestNFShmHashMapWithList
//
// -------------------------------------------------------------------------

#pragma once

#include <gtest/gtest.h>
#include "NFComm/NFShmStl/NFShmHashMapWithList.h"
#include <string>
#include <vector>
#include <algorithm>
#include <chrono>
#include <cmath>

/**
 * @file TestNFShmHashMapWithList.h
 * @brief NFShmHashMapWithList的单元测试，重点测试新增的value排序功能
 * 
 * 测试覆盖范围：
 * 1. sort_list() - 按值升序排序
 * 2. sort_list() - 按值降序排序
 * 3. sort_list(comp) - 使用自定义比较器按值排序
 * 4. 与原有sort_list()的兼容性测试
 * 5. 复杂对象的value排序测试
 * 6. 性能对比测试
 */

// ==================== 测试用数据结构 ====================

/**
 * @brief 用于测试复杂对象value排序的用户信息结构
 */
struct UserInfo
{
    int age;
    std::string department;
    double salary;

    UserInfo() : age(0), salary(0.0)
    {
    }

    UserInfo(int a, const std::string& d, double s) : age(a), department(d), salary(s)
    {
    }

    bool operator==(const UserInfo& other) const
    {
        return age == other.age && department == other.department && salary == other.salary;
    }

    bool operator<(const UserInfo& other) const
    {
        if (age != other.age)
            return age < other.age;
        if (department != other.department)
            return department < other.department;
        return salary < other.salary;
    }
};

// ==================== 基础Value排序测试 ====================

/**
 * @brief 测试基础的value排序功能：升序、降序
 */
TEST(NFShmHashMapWithListTest, BasicValueSorting)
{
    printf("========== BasicValueSorting Test ==========\n");

    NFShmHashMapWithList<std::string, int, 100> scoreMap;
    scoreMap.CreateInit();

    // 插入测试数据
    scoreMap["Alice"] = 95;
    scoreMap["Bob"] = 87;
    scoreMap["Charlie"] = 92;
    scoreMap["David"] = 89;
    scoreMap["Eve"] = 98;

    printf("Original insertion order:\n");
    for (auto it = scoreMap.list_begin(); it != scoreMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
    }

    // 测试1：按值升序排序（使用明确的by_value方法）
    scoreMap.sort_list();

    printf("\nAfter sort_list() (ascending):\n");
    std::vector<int> ascending_values;
    for (auto it = scoreMap.list_begin(); it != scoreMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        ascending_values.push_back(it->second);
    }

    // 验证升序排序结果
    std::vector<int> expected_ascending = {87, 89, 92, 95, 98};
    EXPECT_EQ(ascending_values, expected_ascending);

    // 测试2：按值降序排序（使用自定义比较器）
    scoreMap.sort_list([](const int& a, const int& b)
    {
        return a > b; // 降序比较
    });

    printf("\nAfter sort_list() with descending comparator:\n");
    std::vector<int> descending_values;
    for (auto it = scoreMap.list_begin(); it != scoreMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        descending_values.push_back(it->second);
    }

    // 验证降序排序结果
    std::vector<int> expected_descending = {98, 95, 92, 89, 87};
    EXPECT_EQ(descending_values, expected_descending);

    // 验证哈希表功能仍然正常
    EXPECT_EQ(scoreMap.size(), 5);
    EXPECT_EQ(scoreMap["Alice"], 95);
    EXPECT_EQ(scoreMap["Bob"], 87);
    EXPECT_EQ(scoreMap.count("Charlie"), 1);

    printf("BasicValueSorting test passed\n");
}

/**
 * @brief 测试按键排序功能：升序、降序、自定义比较器
 */
TEST(NFShmHashMapWithListTest, BasicKeySorting)
{
    printf("========== BasicKeySorting Test ==========\n");

    NFShmHashMapWithList<std::string, int, 100> nameScoreMap;
    nameScoreMap.CreateInit();

    // 插入测试数据（键的字母顺序与插入顺序不同）
    nameScoreMap["Zebra"] = 85;
    nameScoreMap["Alice"] = 95;
    nameScoreMap["Charlie"] = 92;
    nameScoreMap["Bob"] = 87;
    nameScoreMap["David"] = 89;

    printf("Original insertion order:\n");
    for (auto it = nameScoreMap.list_begin(); it != nameScoreMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
    }

    // 测试1：按键升序排序
    nameScoreMap.sort_list_by_key();

    printf("\nAfter sort_list_by_key() (ascending):\n");
    std::vector<std::string> ascending_keys;
    for (auto it = nameScoreMap.list_begin(); it != nameScoreMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        ascending_keys.push_back(it->first);
    }

    // 验证键按字母升序排列
    std::vector<std::string> expected_ascending = {"Alice", "Bob", "Charlie", "David", "Zebra"};
    EXPECT_EQ(ascending_keys, expected_ascending);

    // 测试2：按键降序排序（使用自定义比较器）
    nameScoreMap.sort_list_by_key([](const std::string& a, const std::string& b) {
        return a > b;  // 降序比较
    });

    printf("\nAfter sort_list_by_key() (descending):\n");
    std::vector<std::string> descending_keys;
    for (auto it = nameScoreMap.list_begin(); it != nameScoreMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        descending_keys.push_back(it->first);
    }

    // 验证键按字母降序排列
    std::vector<std::string> expected_descending = {"Zebra", "David", "Charlie", "Bob", "Alice"};
    EXPECT_EQ(descending_keys, expected_descending);

    // 验证哈希查找仍然正常工作
    EXPECT_EQ(nameScoreMap.size(), 5);
    EXPECT_EQ(nameScoreMap["Alice"], 95);
    EXPECT_EQ(nameScoreMap["Bob"], 87);
    EXPECT_EQ(nameScoreMap.count("Charlie"), 1);

    printf("BasicKeySorting test passed\n");
}

/**
 * @brief 测试sort_list()默认行为（应该按key排序）
 */
TEST(NFShmHashMapWithListTest, DefaultSortListBehavior)
{
    printf("========== DefaultSortListBehavior Test ==========\n");

    NFShmHashMapWithList<std::string, int, 100> testMap;
    testMap.CreateInit();

    // 插入测试数据（键的字母顺序与插入顺序不同）
    testMap["Zebra"] = 85;
    testMap["Alice"] = 95;
    testMap["Charlie"] = 92;
    testMap["Bob"] = 87;

    printf("Original insertion order:\n");
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
    }

    // 测试：默认的sort_list()应该按value排序（根据接口定义）
    testMap.sort_list();

    printf("\nAfter sort_list() (should be sorted by value - default behavior):\n");
    std::vector<int> sorted_values;
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        sorted_values.push_back(it->second);
    }

    // 验证默认sort_list()按value排序
    std::vector<int> expected_values = {85, 87, 92, 95};
    EXPECT_EQ(sorted_values, expected_values);

    // 验证这与sort_list_by_value()的结果一致
    NFShmHashMapWithList<std::string, int, 100> testMap2;
    testMap2.CreateInit();
    testMap2["Zebra"] = 85;
    testMap2["Alice"] = 95;
    testMap2["Charlie"] = 92;
    testMap2["Bob"] = 87;
    
    testMap2.sort_list_by_value();
    
    auto it1 = testMap.list_begin();
    auto it2 = testMap2.list_begin();
    while (it1 != testMap.list_end() && it2 != testMap2.list_end()) {
        EXPECT_EQ(it1->first, it2->first);  // 键应该相同
        EXPECT_EQ(it1->second, it2->second); // 值也应该相同
        ++it1;
        ++it2;
    }

    // 验证与sort_list_by_key()结果不同（证明默认确实按value排序）
    NFShmHashMapWithList<std::string, int, 100> testMap3;
    testMap3.CreateInit();
    testMap3["Zebra"] = 85;
    testMap3["Alice"] = 95;
    testMap3["Charlie"] = 92;
    testMap3["Bob"] = 87;
    
    testMap3.sort_list_by_key();
    
    std::vector<std::string> sorted_keys_by_key;
    for (auto it = testMap3.list_begin(); it != testMap3.list_end(); ++it)
    {
        sorted_keys_by_key.push_back(it->first);
    }
    
    std::vector<std::string> expected_keys = {"Alice", "Bob", "Charlie", "Zebra"};
    EXPECT_EQ(sorted_keys_by_key, expected_keys);
    
    // 验证默认value排序和key排序的第一个元素确实不同
    EXPECT_EQ(sorted_keys_by_key[0], "Alice"); // key排序时Alice在前
    // 而value排序时获得的keys顺序应该不同（通过values[0]对应的key验证）
    std::string first_key_in_value_sort;
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        if (it->second == 85) { // 最小value对应的key
            first_key_in_value_sort = it->first;
            break;
        }
    }
    EXPECT_EQ(first_key_in_value_sort, "Zebra"); // value排序时Zebra在前（因为85是最小值）

    printf("DefaultSortListBehavior test passed\n");
}

/**
 * @brief 测试自定义value比较器排序
 */
TEST(NFShmHashMapWithListTest, CustomValueComparator)
{
    printf("========== CustomValueComparator Test ==========\n");

    NFShmHashMapWithList<std::string, int, 100> dataMap;
    dataMap.CreateInit();

    // 插入包含正负数的测试数据
    dataMap["A"] = -15;
    dataMap["B"] = 23;
    dataMap["C"] = -8;
    dataMap["D"] = 31;
    dataMap["E"] = -42;
    dataMap["F"] = 5;

    printf("Original data:\n");
    for (auto it = dataMap.list_begin(); it != dataMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
    }

    // 测试1：按绝对值升序排序
    dataMap.sort_list([](const int& a, const int& b)
    {
        return std::abs(a) < std::abs(b);
    });

    printf("\nAfter sorting by absolute value (ascending):\n");
    std::vector<int> abs_values;
    for (auto it = dataMap.list_begin(); it != dataMap.list_end(); ++it)
    {
        printf("  %s: %d (abs: %d)\n", it->first.c_str(), it->second, std::abs(it->second));
        abs_values.push_back(std::abs(it->second));
    }

    // 验证按绝对值排序结果
    std::vector<int> expected_abs = {5, 8, 15, 23, 31, 42};
    EXPECT_EQ(abs_values, expected_abs);

    // 测试2：按值取模10的结果排序
    dataMap.sort_list([](const int& a, const int& b)
    {
        return (a % 10) < (b % 10);
    });

    printf("\nAfter sorting by modulo 10:\n");
    std::vector<int> mod_values;
    for (auto it = dataMap.list_begin(); it != dataMap.list_end(); ++it)
    {
        printf("  %s: %d (mod 10: %d)\n", it->first.c_str(), it->second, it->second % 10);
        mod_values.push_back(it->second % 10);
    }

    // 验证模10排序结果是升序的
    EXPECT_TRUE(std::is_sorted(mod_values.begin(), mod_values.end()));

    printf("CustomValueComparator test passed\n");
}

/**
 * @brief 测试复杂对象的value排序
 */
TEST(NFShmHashMapWithListTest, ComplexObjectValueSorting)
{
    printf("========== ComplexObjectValueSorting Test ==========\n");

    NFShmHashMapWithList<int, UserInfo, 100> userMap;
    userMap.CreateInit();

    // 插入用户数据
    userMap[1001] = UserInfo(25, "Engineering", 75000.0);
    userMap[1002] = UserInfo(30, "Marketing", 68000.0);
    userMap[1003] = UserInfo(22, "Engineering", 72000.0);
    userMap[1004] = UserInfo(35, "Sales", 85000.0);
    userMap[1005] = UserInfo(28, "Marketing", 71000.0);
    userMap[1006] = UserInfo(26, "Engineering", 74000.0);

    printf("Original user data:\n");
    for (auto it = userMap.list_begin(); it != userMap.list_end(); ++it)
    {
        printf("  ID %d: %d years, %s, $%.0f\n", it->first, it->second.age, it->second.department.c_str(), it->second.salary);
    }

    // 测试1：按年龄排序（使用sort_list_by_value直接比较UserInfo对象）
    userMap.sort_list_by_value([](const UserInfo& a, const UserInfo& b)
    {
        return a.age < b.age;
    });

    printf("\nAfter sorting by age:\n");
    std::vector<int> ages;
    for (auto it = userMap.list_begin(); it != userMap.list_end(); ++it)
    {
        printf("  ID %d: %d years, %s, $%.0f\n", it->first, it->second.age, it->second.department.c_str(), it->second.salary);
        ages.push_back(it->second.age);
    }

    // 验证年龄排序结果
    EXPECT_TRUE(std::is_sorted(ages.begin(), ages.end()));

    // 测试2：按薪资降序排序（使用sort_list_by_value直接比较UserInfo对象）
    userMap.sort_list_by_value([](const UserInfo& a, const UserInfo& b)
    {
        return a.salary > b.salary; // 降序
    });

    printf("\nAfter sorting by salary (descending):\n");
    std::vector<double> salaries;
    for (auto it = userMap.list_begin(); it != userMap.list_end(); ++it)
    {
        printf("  ID %d: %d years, %s, $%.0f\n", it->first, it->second.age, it->second.department.c_str(), it->second.salary);
        salaries.push_back(it->second.salary);
    }

    // 验证薪资降序排序结果
    EXPECT_TRUE(std::is_sorted(salaries.begin(), salaries.end(), std::greater<double>()));

    // 测试3：复合排序：先按部门，再按年龄（使用sort_list_by_value直接比较UserInfo对象）
    userMap.sort_list_by_value([](const UserInfo& a, const UserInfo& b)
    {
        if (a.department != b.department)
        {
            return a.department < b.department;
        }
        return a.age < b.age;
    });

    printf("\nAfter sorting by department then age:\n");
    std::string prev_dept = "";
    int prev_age = 0;
    bool is_correctly_sorted = true;
    for (auto it = userMap.list_begin(); it != userMap.list_end(); ++it)
    {
        printf("  ID %d: %d years, %s, $%.0f\n", it->first, it->second.age, it->second.department.c_str(), it->second.salary);

        // 验证复合排序的正确性
        if (!prev_dept.empty())
        {
            if (it->second.department < prev_dept || (it->second.department == prev_dept && it->second.age < prev_age))
            {
                is_correctly_sorted = false;
            }
        }
        prev_dept = it->second.department;
        prev_age = it->second.age;
    }

    EXPECT_TRUE(is_correctly_sorted);
    printf("ComplexObjectValueSorting test passed\n");
}

/**
 * @brief 测试与原有sort_list()方法的兼容性和对比
 */
TEST(NFShmHashMapWithListTest, SortListCompatibility)
{
    printf("========== SortListCompatibility Test ==========\n");

    NFShmHashMapWithList<std::string, int, 100> testMap;
    testMap.CreateInit();

    // 插入测试数据
    testMap["zebra"] = 10;
    testMap["apple"] = 30;
    testMap["banana"] = 20;
    testMap["cherry"] = 40;

    printf("Original data:\n");
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
    }

    // 保存原始数据，用于恢复测试
    std::vector<std::pair<std::string, int>> original_data;
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        original_data.emplace_back(it->first, it->second);
    }

    // 测试1：使用sort_list_by_key按key排序
    testMap.sort_list_by_key();

    printf("\nAfter sort_list_by_key() (ascending):\n");
    std::vector<std::string> keys_after_key_sort;
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        keys_after_key_sort.push_back(it->first);
    }

    std::vector<std::string> expected_key_order = {"apple", "banana", "cherry", "zebra"};
    EXPECT_EQ(keys_after_key_sort, expected_key_order);

    // 恢复原始数据顺序
    testMap.clear();
    for (const auto& pair : original_data)
    {
        testMap[pair.first] = pair.second;
    }

    // 测试2：使用sort_list()按value排序（默认行为）
    testMap.sort_list();

    printf("\nAfter sort_list() (default - by value):\n");
    std::vector<int> values_after_value_sort;
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        values_after_value_sort.push_back(it->second);
    }

    std::vector<int> expected_value_order = {10, 20, 30, 40};
    EXPECT_EQ(values_after_value_sort, expected_value_order);

    // 恢复原始数据顺序
    testMap.clear();
    for (const auto& pair : original_data)
    {
        testMap[pair.first] = pair.second;
    }

    // 测试3：使用sort_list(comp)按value排序（降序）
    testMap.sort_list([](const int& a, const int& b)
    {
        return a > b; // 按value降序排序
    });

    printf("\nAfter sort_list(comp) (by value descending):\n");
    std::vector<int> values_after_custom_sort;
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        values_after_custom_sort.push_back(it->second);
    }

    std::vector<int> expected_value_desc_order = {40, 30, 20, 10};
    EXPECT_EQ(values_after_custom_sort, expected_value_desc_order);

    // 测试4：验证sort_list()默认按value排序与sort_list_by_value()一致
    testMap.clear();
    for (const auto& pair : original_data)
    {
        testMap[pair.first] = pair.second;
    }

    testMap.sort_list_by_value();
    
    std::vector<int> values_by_value_method;
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        values_by_value_method.push_back(it->second);
    }
    
    EXPECT_EQ(values_after_value_sort, values_by_value_method);

    printf("SortListCompatibility test passed\n");
}

/**
 * @brief 测试边界情况：空容器、单元素、相同值等
 */
TEST(NFShmHashMapWithListTest, EdgeCases)
{
    printf("========== EdgeCases Test ==========\n");

    // 测试1：空容器排序
    printf("Test 1: Empty container sorting\n");
    {
        NFShmHashMapWithList<std::string, int, 10> emptyMap;
        emptyMap.CreateInit();

        // 对空容器排序应该不会出错
        emptyMap.sort_list();
        emptyMap.sort_list();
        emptyMap.sort_list([](const int& a, const int& b) { return a < b; });

        EXPECT_EQ(emptyMap.size(), 0);
        EXPECT_TRUE(emptyMap.empty());
        printf("Empty container sorting passed\n");
    }

    // 测试2：单元素排序
    printf("Test 2: Single element sorting\n");
    {
        NFShmHashMapWithList<std::string, int, 10> singleMap;
        singleMap.CreateInit();
        singleMap["only"] = 42;

        singleMap.sort_list();
        EXPECT_EQ(singleMap.size(), 1);
        EXPECT_EQ(singleMap["only"], 42);

        singleMap.sort_list();
        EXPECT_EQ(singleMap.size(), 1);
        EXPECT_EQ(singleMap["only"], 42);

        printf("Single element sorting passed\n");
    }

    // 测试3：相同值排序
    printf("Test 3: Same value sorting\n");
    {
        NFShmHashMapWithList<std::string, int, 10> sameValueMap;
        sameValueMap.CreateInit();

        sameValueMap["first"] = 100;
        sameValueMap["second"] = 100;
        sameValueMap["third"] = 100;

        // 保存原始顺序
        std::vector<std::string> original_order;
        for (auto it = sameValueMap.list_begin(); it != sameValueMap.list_end(); ++it)
        {
            original_order.push_back(it->first);
        }

        sameValueMap.sort_list();

        // 相同值的情况下，应该保持稳定排序（原有顺序）
        std::vector<std::string> after_sort_order;
        for (auto it = sameValueMap.list_begin(); it != sameValueMap.list_end(); ++it)
        {
            after_sort_order.push_back(it->first);
        }

        // 所有值应该相同
        for (auto it = sameValueMap.list_begin(); it != sameValueMap.list_end(); ++it)
        {
            EXPECT_EQ(it->second, 100);
        }

        printf("Same value sorting passed\n");
    }

    printf("EdgeCases test passed\n");
}

/**
 * @brief 性能测试：对比不同排序方法的性能
 */
TEST(NFShmHashMapWithListTest, PerformanceComparison)
{
    printf("========== PerformanceComparison Test ==========\n");

    constexpr int TEST_SIZE = 1000;
    NFShmHashMapWithList<int, int, TEST_SIZE + 100> perfMap;
    perfMap.CreateInit();

    // 准备测试数据
    std::vector<int> test_keys;
    for (int i = 1; i <= TEST_SIZE; ++i)
    {
        test_keys.push_back(i);
    }

    // 随机打乱数据
    std::random_device rd;
    std::mt19937 gen(rd());
    std::shuffle(test_keys.begin(), test_keys.end(), gen);

    // 插入数据
    for (int key : test_keys)
    {
        perfMap[key] = (key * 31 + 17) % 1000; // 生成伪随机值
    }

    printf("Performance test with %d elements:\n", TEST_SIZE);

    // 测试sort_list性能
    auto start = std::chrono::high_resolution_clock::now();
    perfMap.sort_list();
    auto end = std::chrono::high_resolution_clock::now();
    auto value_sort_time = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

    // 验证排序正确性
    std::vector<int> sorted_values;
    for (auto it = perfMap.list_begin(); it != perfMap.list_end(); ++it)
    {
        sorted_values.push_back(it->second);
    }
    EXPECT_TRUE(std::is_sorted(sorted_values.begin(), sorted_values.end()));

    printf("sort_list() took %lld microseconds\n", value_sort_time.count());

    // 对比等价的sort_list性能
    // 重新打乱数据
    perfMap.clear();
    for (int key : test_keys)
    {
        perfMap[key] = (key * 31 + 17) % 1000;
    }

    start = std::chrono::high_resolution_clock::now();
    perfMap.sort_list([](const int& a, const int& b)
    {
        return a < b; // 等价的value排序
    });
    end = std::chrono::high_resolution_clock::now();
    auto traditional_sort_time = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

    printf("Equivalent sort_list() took %lld microseconds\n", traditional_sort_time.count());

    // 计算性能差异
    double performance_ratio = static_cast<double>(traditional_sort_time.count()) / value_sort_time.count();
    printf("Performance ratio (traditional/new): %.2fx\n", performance_ratio);

    // 新方法应该不会明显慢于传统方法（允许20%的性能差异）
    EXPECT_LT(value_sort_time.count(), traditional_sort_time.count() * 1.2);

    printf("PerformanceComparison test passed\n");
}
